<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $企业微信企业客户API
*/
namespace core;
defined('BY_JYA') or exit('error');
class wxwork_userapi{
	protected $work_weixin = null;
	public function __construct($wxworkapp_id=0){
		if(!$wxworkapp_id){
			$wxworkapp_id=$_SESSION['wxworkapp_id'];
		}
		if($wxworkapp_id){
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('id'=>$wxworkapp_id,'uniacid'=>$_SESSION['uniacid']),'id');
		}
		if(!$wxworkapp_id && $_SESSION['current_plugin'] && $_SESSION['current_plugin']!='core'){
			$pid=pdo_getcolumn('core_plugins',array('name'=>$_SESSION['current_plugin']),'id');
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('pid'=>$pid,'uniacid'=>$_SESSION['uniacid']),'id');
			$_SESSION['wxworkapp_id']=$wxworkapp_id;
		}
		if(!$wxworkapp_id){
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('default'=>1,'uniacid'=>$_SESSION['uniacid']),'id');
		}
		if(!$wxworkapp_id){
			$wxworkapp_id=pdo_getcolumn('core_account_wxwork_app',array('uniacid'=>$_SESSION['uniacid']),'id');
		}
		$this->uniacid=$_SESSION['uniacid'];
		if($wxworkapp_id){
			$_SESSION['wxworkapp_id']=$wxworkapp_id;
			$this->work_weixin=pdo_get('core_account_wxwork_app',array('id'=>$wxworkapp_id));
			if($this->work_weixin['merchid'] && $_SESSION['this']!='manage'){
				$_SESSION['onemerchid']=$this->work_weixin['merchid'];
			}
			$this->work_weixin['corpid']=pdo_getcolumn('core_account_wxwork',array('id'=>$this->work_weixin['wxwork_id']),'appid');
		}else{
			exi('请传入应用ID,或创建一个属于本场景下的应用！','error','core/wxwork.app/');
		}
		if(empty($this->work_weixin['corpid'])){
			if($_SESSION['this']=='manage'){
					exi('请先添加企业微信！并设置企业微信APPID','error','core/wxwork.list/');
			}else{
					return false;
					exi('请先添加企业微信。','error');
			}
		}
		if (empty($this->work_weixin['appid'])){
			exi('未绑定应用appid','error');
		}
		if (empty($this->work_weixin['corpid'])){
			exi('企业微信的corpid，不能为空！','error');
		}
		if($this->work_weixin['permanent_code']){
			$this->work_weixin['saasid']=pdo_getcolumn('core_open_plugin',array('pid'=>$this->work_weixin['pid'],'uniacid'=>$_SESSION['uniacid'],'isplugin'=>0),'id');
			$this->suite_access_token=model('core/wxwork_api',$this->work_weixin['saasid'])->get_suite_token();
			if($this->work_weixin['saastype']==1){
				$this->work_weixin['appsecret']=$this->work_weixin['permanent_code'];
			}
		}
		if($this->work_weixin['expire']<TIMESTAMP){
			$this->getAccessToken();
		}
	}
	public function get_corpid(){
		return $this->work_weixin['corpid'];
	}
	public function get_wxworkid(){
		return $this->work_weixin['wxwork_id'];
	}
	public function getAccessToken($continue=false){//获取access_token
		if($this->work_weixin['expire']>TIMESTAMP && !$continue){
			return $this->work_weixin['access_token'];
		}
		//saas安装
		if($this->work_weixin['permanent_code'] && $this->work_weixin['saastype']!=1){
			$url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?suite_access_token=".$this->suite_access_token;
			$post=array(
				'auth_corpid'=>$this->work_weixin['corpid'],
				'permanent_code'=>$this->work_weixin['permanent_code'],
			);
		}else{
			if(!$this->work_weixin['appsecret']){
				return false;
			}else{
				$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->work_weixin['corpid']."&corpsecret=".$this->work_weixin['appsecret'];
			}
		}
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取企业微信应用凭证, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		if(empty($content['access_token'])) {
			exi('获取企业微信应用凭证, 请稍后重试！错误代码-' . $content['errcode'] . '，错误信息-' . $content['errmsg'],'error');
		}
		$this->work_weixin['access_token'] = $content['access_token'];
		$this->work_weixin['expire'] = TIMESTAMP + $content['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',array('access_token'=>$this->work_weixin['access_token'],'expire'=>$this->work_weixin['expire']),array('id'=>$this->work_weixin['id']));
		return $content['access_token'];
	}
	public function getTXAccessToken($continue=false){//获取access_token
		if($this->work_weixin['txexpire']>TIMESTAMP && !$continue){
			return $this->work_weixin['txaccess_token'];
		}
		if(!$this->work_weixin['txsecret']){
			return false;
		}else{
			$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->work_weixin['corpid']."&corpsecret=".$this->work_weixin['txsecret'];
		}
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取企业微信应用凭证, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		if(empty($content['access_token'])) {
			exi('获取企业微信应用凭证, 请稍后重试！错误代码-' . $content['errcode'] . '，错误信息-' . $content['errmsg'],'error');
		}
		$this->work_weixin['txaccess_token'] = $content['access_token'];
		$this->work_weixin['txexpire'] = TIMESTAMP + $content['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',array('txaccess_token'=>$this->work_weixin['txaccess_token'],'txexpire'=>$this->work_weixin['txexpire']),array('id'=>$this->work_weixin['id']));
		return $content['access_token'];
	}
	public function getLXAccessToken($continue=false){//获取access_token
		if($this->work_weixin['lxexpire']>TIMESTAMP && !$continue){
			return $this->work_weixin['lxaccess_token'];
		}
		if(!$this->work_weixin['lxsecret']){
			return false;
		}else{
			$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->work_weixin['corpid']."&corpsecret=".$this->work_weixin['lxsecret'];
		}
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取联系客户应用凭证, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		if(empty($content['access_token'])) {
			exi('获取联系客户应用凭证, 请稍后重试！错误代码-' . $content['errcode'] . '，错误信息-' . $content['errmsg'],'error');
		}
		$this->work_weixin['lxaccess_token'] = $content['access_token'];
		$this->work_weixin['lxexpire'] = TIMESTAMP + $content['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',array('lxaccess_token'=>$this->work_weixin['lxaccess_token'],'lxexpire'=>$this->work_weixin['lxexpire']),array('id'=>$this->work_weixin['id']));
		return $content['access_token'];
	}
	//获取客户列表
	public function get_member_list($userid){
		if(!$userid){
			exi('请传入企业成员的ID','error');
		}
		if($this->work_weixin['lxsecret']){
			if($this->work_weixin['lxexpire']<TIMESTAMP){
				$this->getLXAccessToken();
			}
			$access_token=$this->work_weixin['lxaccess_token'];
		}else{
			$access_token='{access_token}';
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=".$access_token."&userid=".$userid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取客户列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		$list=$content['external_userid'];
		return $list;
	}
	//获取客户详情
	public function get_member_item($external_userid){
		if(!$external_userid){
			exi('请传入客户ID','error');
		}
		if($this->work_weixin['lxsecret']){
			if($this->work_weixin['lxexpire']<TIMESTAMP){
				$this->getLXAccessToken();
			}
			$access_token=$this->work_weixin['lxaccess_token'];
		}else{
			$access_token='{access_token}';
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=".$access_token."&external_userid=".$external_userid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取客户详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		$memberitem=$content['external_contact'];
		if($content['follow_user']){
			$memberitem['follow_user']=$content['follow_user'][0]?:$content['follow_user'];
		}
		return $memberitem;
	}
	//批量获取客户详情
	public function get_batch_member($external_userid,$cursor='',$limit=50){
		if(!$external_userid){
			exi('请传入员工ID','error');
		}
		if($this->work_weixin['lxsecret']){
			if($this->work_weixin['lxexpire']<TIMESTAMP){
				$this->getLXAccessToken();
			}
			$access_token=$this->work_weixin['lxaccess_token'];
		}else{
			$access_token='{access_token}';
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=".$access_token;
		$post=array(
			'userid'=>$external_userid,
			'cursor'=>$cursor,
			'limit'=>$limit,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			if($content['errcode']=='48002'){
				exi('没有权限：移步企业微信后台--客户联系--客户--API(点击展开)--可调用应用--选择本SCRM应用','error');
			}elseif($content['errcode']=='60111'){
				exi('批量获取客户详情失败, 员工ID异常（可能该员工已离职了，请同步一下员工！）：'.$content['errmsg'],'error');
			}elseif($content['errcode']!='40003'){
				exi('批量获取客户详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
			}
		}
		return $content;
	}
	//修改客户备注信息
	public function set_member_remark($params){
		if(!$params['external_userid']){
			exi('请传入客户ID','error');
		}
		if($this->work_weixin['lxsecret']){
			if($this->work_weixin['lxexpire']<TIMESTAMP){
				$this->getLXAccessToken();
			}
			$access_token=$this->work_weixin['lxaccess_token'];
		}else{
			$access_token='{access_token}';
		}
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/remark?access_token=".$access_token;
		$post=array(
			'userid'=>$params['userid'],
			'external_userid'=>$params['external_userid'],
			'remark'=>$params['remark'],
			'description'=>$params['description'],
			'remark_company'=>$params['remark_company'],
			'remark_mobiles'=>$params['remark_mobiles'],
			'remark_pic_mediaid'=>$params['remark_pic_mediaid'],
		);
		$content=$this->request($url,$post);
		if($content['errcode']){
			exi('修改客户备注信息失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//更新群欢迎语
	public function upqun_welcome($template_id,$data=array()){
		$post=array(
			'text'=>$data['text'],
		);
		if(!$template_id){			
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/add?access_token={access_token}";
		}else{
			$post['template_id']=$template_id;
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/group_welcome_template/edit?access_token={access_token}";
		}
		$post=cfc('tools')->jy_encode($post);
		$content=$this->request($url,$post,true);
		if($content['errcode']){
			exi('更新群欢迎语失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['template_id']?:$template_id;
	}
	//获取部门列表
	public function get_worker_bumen($bumenid=0){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={access_token}&id=".$bumenid;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取部门列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['department'];
	}
	//获取员工列表
	public function get_worker_batch($bumenid=0,$fetch_child=1){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token={access_token}&department_id=".$bumenid."&fetch_child=".$fetch_child;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取员工列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['userlist'];
	}
	//获取员工列表详情
	public function get_worker_batchinfo($bumenid=0,$fetch_child=1){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={access_token}&department_id=".$bumenid."&fetch_child=".$fetch_child;
		$content = $this->request($url);
		if($content['errcode']){
			if($content['errcode']=='60003'){
				return 60003;
			}
			exi('获取员工列表详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['userlist'];
	}
	//获取访问用户身份
	public function get_worker_user_ticket($code=''){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token={access_token}&code=".$code;
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取访问用户身份！错误详情：'.$content['errmsg'],'error');
		}
		return $content['user_ticket'];
	}
	//获取员工详情
	public function get_worker_info($user_ticket=''){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token={access_token}";
		$post=array('user_ticket'=>$user_ticket);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取员工详情！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//创建员工
	public function worker_create($data=array()){
		if(!$data['userid']){
			exi('请填写正确的员工userid（账号）','error');
		}
		if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=".$this->work_weixin['txaccess_token'];
		$post=array(
			'userid'=>trim($data['userid']),
			'name'=>trim($data['name']),
			'alias'=>trim($data['alias']),
			'telephone'=>trim($data['telephone']),
			'mobile'=>trim($data['mobile']),
			'email'=>trim($data['email']),
			'position'=>trim($data['position']),
			'external_position'=>trim($data['external_position']),
			'avatar'=>trim($data['avatar']),
			'address'=>trim($data['address']),
			'gender'=>intval($data['gender']),
			'main_department'=>intval($data['main_department']),
			//'department'=>json_decode($data['department'],true),
			'extattr'=>json_decode($postdata['extattr'],true),
			'external_profile'=>json_decode($postdata['external_profile'],true),
		);
		$content = $this->request($url,$post);
		if($content['errcode']=='60011'){
			exi('添加员工失败, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('添加员工失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//修改员工
	public function worker_update($data=array()){
		if(!$data['userid']){
			exi('请填写正确的员工userid（账号）','error');
		}
    	if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=".$this->work_weixin['txaccess_token'];
		$post=array(
			'userid'=>trim($data['userid']),
			'name'=>trim($data['name']),
			'alias'=>trim($data['alias']),
			'telephone'=>trim($data['telephone']),
			'mobile'=>trim($data['mobile']),
			'email'=>trim($data['email']),
			'position'=>trim($data['position']),
			'external_position'=>trim($data['external_position']),
			'avatar'=>trim($data['avatar']),
			'address'=>trim($data['address']),
			'gender'=>intval($data['gender']),
			'main_department'=>intval($data['main_department']),
			//'department'=>json_decode($data['department'],true),
			'extattr'=>json_decode($postdata['extattr'],true),
			'external_profile'=>json_decode($postdata['external_profile'],true),
		);
		$content = $this->request($url,$post);
		if($content['errcode']=='60011'){
			exi('修改员工失败, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('修改员工失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//删除员工
	public function worker_delete($userid=''){
		if(!$userid){
			exi('请传入员工userid！','error');
		}
    	if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$access_token=$this->work_weixin['txaccess_token'];
		$url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=".$access_token."&userid=".$userid;
		$content = $this->request($url);
		if($content['errcode']=='60011'){
			exi('删除员工失败, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('删除员工失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//创建部门
	public function bumen_create($data=array()){
    	if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$access_token=$this->work_weixin['txaccess_token'];
		$url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=".$access_token;
		$post=array(
			'name'=>trim($postdata['title']),
			'name_en'=>trim($postdata['name_en']),
			'status'=>trim($postdata['status']),
			'parentid'=>trim($postdata['parentid']),
			'order'=>trim($postdata['order']),
		);
		$content = $this->request($url,$post);
		if($content['errcode']=='60011'){
			exi('创建部门失败, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('创建部门失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//修改部门
	public function bumen_update($data=array()){
    	if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$access_token=$this->work_weixin['txaccess_token'];
		$url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=".$access_token;
		$post=array(
			'id'=>$item['bumenid'],
			'name'=>trim($postdata['title']),
			'name_en'=>trim($postdata['name_en']),
			'status'=>trim($postdata['status']),
			'parentid'=>trim($postdata['parentid']),
			'order'=>trim($postdata['order']),
		);
		$content = $this->request($url,$post);
		if($content['errcode']=='60011'){
			exi('修改部门, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('修改部门, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//删除部门
	public function bumen_delete($id=''){
		if(!$id){
			exi('请传入部门ID！','error');
		}
    	if($this->work_weixin['txexpire']<TIMESTAMP){
    		$this->getTXAccessToken();
    	}
    	$access_token=$this->work_weixin['txaccess_token'];
		$url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=".$access_token."&id=".$id;
		$content = $this->request($url);
		if($content['errcode']=='60011'){
			exi('删除部门, 没有删除权限：'.$content['errmsg'],'error');
		}
		if($content['errcode'] && $content['errcode']!='60111'){
			exi('删除部门, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//获取标签列表
	public function get_worker_tags(){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token={access_token}";
		$content = $this->request($url);
		if($content['errcode']){
			exi('获取标签列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['taglist'];
	}
	//获取客户标签库
	public function get_member_tags($tag_id=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token={access_token}";
		$post=array(
			'tag_id'=>$tag_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取企业标签库失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//编辑客户标签
	public function edit_member_tags($post=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag?access_token={access_token}";
		$post=array(
			'id'=>$post['id'],
			'name'=>$post['name'],
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('编辑企业标签失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//add客户标签
	public function add_member_tags($post=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token={access_token}";
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('添加企业标签失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//del客户标签
	public function del_member_tags($post=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token={access_token}";
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('删除企业标签失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//获取客户标签库
	public function mark_member_tags($params=array()){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token={access_token}";
		$post=array(
			'userid'=>$params['userid'],
			'external_userid'=>$params['external_userid'],
			'add_tag'=>$params['add_tag'],
			'remove_tag'=>$params['remove_tag'],
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('编辑企业标签库失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['tag_group'];
	}
	//获取离职成员客户
	public function get_dimissionworker_members($page_id=0,$cursor='',$page_size=100){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_unassigned_list?access_token={access_token}";
		$post=array(
			'page_id'=>$page_id,
			'cursor'=>$cursor,
			'page_size'=>$page_size,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取离职成员客户失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取群列表
	public function get_qunlist($userid='',$cursor='',$limit=100){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list?access_token={access_token}";
		$owner_filter=$userid?array('userid_list'=>array(0=>$userid)):array();
		$post=array(
			'limit'=>$limit?:100,
			'cursor'=>$cursor,
			'owner_filter'=>$owner_filter,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取群列表失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取群详情
	public function get_qunitem($chat_id=''){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token={access_token}";
		$post=array(
			'chat_id'=>$chat_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取群详情失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['group_chat'];
	}
	//配置客户联系「联系我」方式
	public function add_contact_way($post,$noexi=false){
		if($post['config_id']){
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/update_contact_way?access_token={access_token}";
		}else{
			$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_contact_way?access_token={access_token}";
		}
		$content = $this->request($url,$post);
		if($content['errcode'] && !$noexi){
			exi('配置客户联系「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content;
	}
	//获取企业已配置的「联系我」方式
	public function get_contact_way($config_id){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_contact_way?access_token={access_token}";
		$post=array(
			'config_id'=>$config_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('获取企业已配置的「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return $content['contact_way'];
	}
	//删除企业已配置的「联系我」方式
	public function del_contact_way($config_id){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_contact_way?access_token={access_token}";
		$post=array(
			'config_id'=>$config_id,
		);
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('删除企业已配置的「联系我」失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//创建企业群发
	public function member_mass($mass){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token={access_token}";
		$mass['tags']=str_array($mass['tags']);
		$external_userid=array();
		foreach($mass['tags'] as $tv){
			$ids=pdo_getall('jy_scrm_member',array('tags like'=>'%'.trim($tv).'%','uniacid'=>$_SESSION['uniacid']),'external_userid','external_userid');
			$resexternal_userid=array_merge($external_userid,$ids);
		}
		if($resexternal_userid){
			foreach($resexternal_userid as $id=>$ev){
				if($id){
					$external_userid[]=$id;
				}
			}
		}
		if(!$external_userid){
			exi('客户对象为空，不能群发！','error');
		}
		$post=array(
			'chat_type'=>'single',
			'external_userid'=>$external_userid,
		);
		$types=array(
			'0'=>'text',
			'1'=>'image',
			'2'=>'voice',
			'3'=>'mpvideo',
			'4'=>'mpnews',
		);
		if($mass['content_type']==0){
			$post['text']['content']=$mass['content'];
		}else{
			if($mass['content_type']==1){
				$content=array(
					'msgtype'=>'image',
					'image'=>array(
						'media_id'=>$mass['content']
					),
				);
			}elseif($mass['content_type']==2){
				$content=array(
					'msgtype'=>'video',
					'video'=>array(
						'media_id'=>$mass['content']
					),
				);
			}elseif($mass['content_type']==3){
				$content=array(
					'msgtype'=>'video',
					'video'=>array(
						'media_id'=>$mass['content']
					),
				);
			}elseif($mass['content_type']==4){
				$mass['lookcontent']=json_encode($mass['lookcontent'],true);
				$link=array();
				foreach($mass['lookcontent'] as $lv){
					$link[]=array(
						'title'=>$lv['title'],
						'picurl'=>tomedia($lv['image']),
						'url'=>custom_url('core/article.list/detail/id='.$lv['id'],true)
					);
				}
				$content=array(
					'msgtype'=>'link',
					'link'=>$link,
				);
			}
			$post['attachments']['content']=$mass['content'];
		}
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('群发失败 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//发送应用消息（只支持员工）
	public function message($post){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}";
		$post['agentid']=$this->work_weixin['appid'];
		$content = $this->request($url,$post);
		if($content['errcode']){
			exi('给员工发送信息失败, 请稍后重试！错误详情：'.$content['errmsg'],'error');
		}
		return true;
	}
	//上传临时素材
	public function upload_media($source,$type='image'){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token={access_token}&type=".$type;
		if(ATTACHMENT_TYPE){
			//远程附件
			$ext=strrchr($source,'.');
			$source=tomedia($source);
			$temp=ROOT_AT.random(30).$ext;
			copy($source,$temp);
		}else{
			$temp=ROOT_AT.$source;
		}
		$post=array('media'=>'@'.$temp);
		$content = $this->request($url,$post,true);
		if(ATTACHMENT_TYPE){
			@unlink($temp);
		}
		if($content['errcode']){
			return error('获取临时素材,错误详情：'.$content['errmsg']);
			//exi('获取临时素材,错误详情：'.$content['errmsg'],'error');
		}
		return $content['media_id']?:'';
	}
	//发送新客户欢迎语
	public function send_welcome_msg($postdata,$noexi=false){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg?access_token={access_token}";
		if($postdata['State']){
			$state=str_array($postdata['State'],'|');
			if($state[0] && $state[1]){
				if($state[0]=='jy_scrm'){
					$msg=model('jy_scrm/model')->jie_state($postdata['State'],$postdata['ExternalUserID'],$postdata['UserID']);
					$giftmsg=model('jy_scrm/model')->giftmsg($postdata['State'],$postdata['ExternalUserID'],$postdata['UserID']);
				}
			}
		}
		if(!$msg && cfc('core')->plugin_exists('jy_scrm')){
			$msg=model('jy_scrm/model')->jie_state($postdata['State'],$postdata['ExternalUserID'],$postdata['UserID']);
			$giftmsg=model('jy_scrm/model')->giftmsg($postdata['State'],$postdata['ExternalUserID'],$postdata['UserID']);
		}
		$attachments=array();
		if($msg && $postdata['WelcomeCode']){
			$post=array(
				'welcome_code'=>$postdata['WelcomeCode'],
			);
			if($msg['text']){
				$post['text']=$msg['text'];
				if($msg['attachments']){
					$post['attachments']=$msg['attachments'];
				}
			}else{
				$attachments[]=$msg;
				$post['attachments']=$attachments;
			}
			if($giftmsg){
				if($giftmsg['text']['content']){
					if($post['text']){
						$post['text']['content'] .="\n".$giftmsg['text']['content'];
					}else{
						$post['text']=$giftmsg['text'];
					}
				}else{
					$attachments[]=$giftmsg;
					$post['attachments']=$attachments;
				}
			}
			$post=cfc('tools')->jy_encode($post);
			$content = $this->request($url,$post);
			if($content['errcode']){
				if($noexi){
					return error('新客户欢迎语,错误详情：'.$content['errmsg']);
				}else{
					exi('新客户欢迎语,错误详情：'.$content['errmsg'],'error');
				}
			}
		}
		return true;
	}
	public function get_user_behavior_data($post,$noexi=false){
		$url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_user_behavior_data?access_token={access_token}";
		$content = $this->request($url,$post);
		if($content['errcode']){
				if($noexi){
					return error('获取「联系客户统计」数据失败：'.$content['errmsg']);
				}else{
					exi('获取「联系客户统计」数据失败：'.$content['errmsg'],'error');
				}
		}
		return $content['behavior_data'];
	}
	//成员添加外部联系人时，回调该事件
	public function add_external_contact($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->add_external_contact($postdata,$noexi);
		}
		return true;
	}
	//成员修改外部联系人的备注、手机号或标签时，回调该事件
	public function edit_external_contact($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->edit_external_contact($postdata,$noexi);
		}
		return true;
	}
	//外部联系人添加了配置了客户联系功能且开启了免验证的成员时（此时成员尚未确认添加对方为好友），回调该事件
	public function add_half_external_contact($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->add_half_external_contact($postdata,$noexi);
		}
		return true;
	}
	//成员删除外部联系人时，回调该事件
	public function del_external_contact($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->del_external_contact($postdata,$noexi);
		}
		return true;
	}
	//成员被外部联系人删除时，回调该事件
	public function del_follow_user($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->del_follow_user($postdata,$noexi);
		}
		return true;
	}
	//外部联系人添加了配置了客户联系功能且开启了免验证的成员时（此时成员尚未确认添加对方为好友），回调该事件
	public function transfer_fail($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->transfer_fail($postdata,$noexi);
		}
		return true;
	}
	public function chat_add($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->chat_add($postdata,$noexi);
		}
		return true;
	}
	public function chat_update($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->chat_update($postdata,$noexi);
		}
		return true;
	}
	public function chat_dismiss($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->chat_dismiss($postdata,$noexi);
		}
		return true;
	}
	public function tag_add($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->tag_add($postdata,$noexi);
		}
		return true;
	}
	public function tag_update($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->tag_update($postdata,$noexi);
		}
		return true;
	}
	public function tag_delete($postdata,$noexi=false){
		$pluginname=pdo_getcolumn('core_plugins',array('id'=>$this->work_weixin['pid']),'name');
		if($pluginname){
			model($pluginname.'/model')->tag_delete($postdata,$noexi);
		}
		return true;
	}
	public function getscheme($operator_userid='',$userid=''){
		$api='https://qyapi.weixin.qq.com/cgi-bin/get_launch_code?access_token={access_token}';
		$post=array(
			'operator_userid'=>$operator_userid,
			'single_chat'=>array('userid'=>$userid),
		);
		$content=$this->request($api,$post);
		if($content['errcode']){
			//exi('打开会话失败：'.$content['errmsg'],'error');
		}
		$res=array(
			'error'=>$content['errcode'],
			'msg'=>'打开会话失败：'.$content['errmsg'],
			'url'=>'wxwork://launch?launch_code='.$content['launch_code']
		);
		return $res;
	}
	public function getJssdkConfig(){//获取jssdk参数
		global $_AR;
		if(!$this->work_weixin['jsticket'] || $this->work_weixin['jsexpire']<TIMESTAMP){
			$this->getJsconfigTicket();
		}
		$nonceStr = random(16);
		$timestamp = TIMESTAMP;
		$url = $_AR['siteurl'];
		$string1 = "jsapi_ticket={$this->work_weixin['jsticket']}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$url}";
		$signature = sha1($string1);
		$config = array(
			"corpid"    => $this->work_weixin['corpid'],
			"agentid"    => $this->work_weixin['appid'],
			"nonceStr"	=> $nonceStr,
			"timestamp" => $timestamp,
			"signature" => $signature,
		);
		return $config;
	}
	public function getJsApiTicket(){
		global $_AR;
		$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={access_token}&type=jsapi";
		$result=$this->request($url);
		$record = array();
		$record['jsticket'] = $result['ticket'];
		$record['jsexpire'] = TIMESTAMP + $result['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',$record,array('id'=>$this->work_weixin['id']));
		$this->work_weixin['jsticket']=$record['jsticket'];
		return true;
	}
	public function getJsconfigTicket(){
		global $_AR;
		$url = "https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token={access_token}&type=agent_config";
		$result=$this->request($url);
		$record = array();
		$record['jsticket'] = $result['ticket'];
		$record['jsexpire'] = TIMESTAMP + $result['expires_in'] - 200;
		pdo_update('core_account_wxwork_app',$record,array('id'=>$this->work_weixin['id']));
		$this->work_weixin['jsticket']=$record['jsticket'];
		return true;
	}
	/*
		执行接口请求
	*/
	private function request($url,$post=array(),$isarray=false){
		if(is_array($post) && !$isarray){
			$post=ijson_encode($post);
		}
		$rurl=str_replace(array('{access_token}','ACCESS_TOKEN'),$this->work_weixin['access_token'],$url);
		$result=cfc('http')->request($rurl,$post);
		$result=@json_decode($result,true);		
		return $result;
	}
	//错误码
	public function error_code($code, $errmsg = '未知错误') {//获取错误详情
		global $_AR;
		$errors = array(
			'-1' => '系统繁忙',
			'0' => '请求成功',
			'300002' => '商品标题太长了！最长14个汉字',
			'300003' => '价格输入不合规（如：现价比原价大、传入价格非数字等）',
			'300018' => '图片尺寸超过300px*300px',
			'300006' => '图片上传失败（如：mediaID过期）',
			'300007' => '线上小程序版本不存在该链接,请重新上传小程序代码！',
			'300022'=>'此房间号不存在',
			'300023'=>'房间状态 拦截（当前房间状态不允许此操作）',
			'300024'=>'商品不存在',
			'300025'=>'商品审核未通过',
			'300026'=>'房间商品数量已经满额',
			'300027'=>'导入商品失败',
			'300028'=>'房间名称违规',
			'300029'=>'主播昵称违规',
			'300030'=>'主播微信号不合法',
			'300031'=>'直播间封面图不合规',
			'300032'=>'直播间分享图违规',
			'300033'=>'添加商品超过直播间上限',
			'300034'=>'主播微信昵称长度不符合要求',
			'300035'=>'主播微信号不存在',
			'300036'=>'主播微信号未实名认证,登录微信搜索--《直播小程序》--实名认证一下即可！',
			'40001' => '获取access_token时AppSecret错误，或者access_token无效',
			'40002' => '不合法的凭证类型',
			'40003' => '不合法的OpenID',
			'40004' => '不合法的媒体文件类型',
			'40005' => '不合法的文件类型',
			'40006' => '不合法的文件大小',
			'40007' => '不合法的媒体文件id',
			'40008' => '不合法的消息类型',
			'40009' => '不合法的图片文件大小',
			'40010' => '不合法的语音文件大小',
			'40011' => '不合法的视频文件大小',
			'40012' => '不合法的缩略图文件大小',
			'40013' => '不合法的APPID',
			'40014' => '不合法的access_token',
			'40015' => '不合法的菜单类型',
			'40016' => '不合法的按钮个数',
			'40017' => '不合法的按钮个数',
			'40018' => '不合法的按钮名字长度',
			'40019' => '不合法的按钮KEY长度',
			'40020' => '不合法的按钮URL长度',
			'40021' => '不合法的菜单版本号',
			'40022' => '不合法的子菜单级数',
			'40023' => '不合法的子菜单按钮个数',
			'40024' => '不合法的子菜单按钮类型',
			'40025' => '不合法的子菜单按钮名字长度',
			'40026' => '不合法的子菜单按钮KEY长度',
			'40027' => '不合法的子菜单按钮URL长度',
			'40028' => '不合法的自定义菜单使用用户',
			'40029' => '不合法的oauth_code',
			'40030' => '不合法的refresh_token',
			'40031' => '不合法的openid列表',
			'40032' => '不合法的openid列表长度',
			'40033' => '不合法的请求字符，不能包含\uxxxx格式的字符',
			'40035' => '不合法的参数',
			'40038' => '不合法的请求格式',
			'40039' => '不合法的URL长度',
			'40050' => '不合法的分组id',
			'40051' => '分组名字不合法',
			'41001' => '缺少access_token参数',
			'41002' => '缺少appid参数',
			'41003' => '缺少refresh_token参数',
			'41004' => '缺少secret参数',
			'41005' => '缺少多媒体文件数据',
			'41006' => '缺少media_id参数',
			'41007' => '缺少子菜单数据',
			'41008' => '缺少oauth code',
			'41009' => '缺少openid',
			'42001' => 'access_token超时',
			'42002' => 'refresh_token超时',
			'42003' => 'oauth_code超时',
			'43001' => '需要GET请求',
			'43002' => '需要POST请求',
			'43003' => '需要HTTPS请求',
			'43004' => '需要接收者关注',
			'43005' => '需要好友关系',
			'44001' => '多媒体文件为空',
			'44002' => 'POST的数据包为空',
			'44003' => '图文消息内容为空',
			'44004' => '文本消息内容为空',
			'45001' => '多媒体文件大小超过限制',
			'45002' => '消息内容超过限制',
			'45003' => '标题字段超过限制',
			'45004' => '描述字段超过限制',
			'45005' => '链接字段超过限制',
			'45006' => '图片链接字段超过限制',
			'45007' => '语音播放时间超过限制',
			'45008' => '图文消息超过限制',
			'45009' => '接口调用超过限制',
			'45010' => '创建菜单个数超过限制',
			'45015' => '回复时间超过限制',
			'45016' => '系统分组，不允许修改',
			'45017' => '分组名字过长',
			'45018' => '分组数量超过上限',
			'45056' => '创建的标签数过多，请注意不能超过100个',
			'45057' => '该标签下粉丝数超过10w，不允许直接删除',
			'45058' => '不能修改0/1/2这三个系统默认保留的标签',
			'45059' => '有粉丝身上的标签数已经超过限制',
			'45157' => '标签名非法，请注意不能和其他标签重名',
			'45158' => '标签名长度超过30个字节',
			'45159' => '非法的标签',
			'46001' => '不存在媒体数据',
			'46002' => '不存在的菜单版本',
			'46003' => '不存在的菜单数据',
			'46004' => '不存在的用户',
			'47001' => '解析JSON/XML内容错误',
			'48001' => 'api功能未授权',
			'50001' => '用户未授权该api',
			'40070' => '基本信息baseinfo中填写的库存信息SKU不合法。',
			'41011' => '必填字段不完整或不合法，参考相应接口。',
			'40056' => '无效code，请确认code长度在20个字符以内，且处于非异常状态（转赠、删除）。',
			'43009' => '无自定义SN权限，请参考开发者必读中的流程开通权限。',
			'43010' => '无储值权限,请参考开发者必读中的流程开通权限。',
			'43011' => '无积分权限,请参考开发者必读中的流程开通权限。',
			'40078' => '无效卡券，未通过审核，已被置为失效。',
			'40079' => '基本信息base_info中填写的date_info不合法或核销卡券未到生效时间。',
			'45021' => '文本字段超过长度限制，请参考相应字段说明。',
			'40080' => '卡券扩展信息cardext不合法。',
			'40097' => '基本信息base_info中填写的参数不合法。',
			'49004' => '签名错误。',
			'43012' => '无自定义cell跳转外链权限，请参考开发者必读中的申请流程开通权限。',
			'40099' => '该code已被核销。',
			'61005' => '缺少接入平台关键数据，等待微信开放平台推送数据，请十分钟后再试或是检查“授权事件接收URL”是否写错（index.php?c=account&amp;a=auth&amp;do=ticket地址中的&amp;符号容易被替换成&amp;amp;）',
			'61023' => '请重新授权接入该小程序',
			'85005'=>'小程序未关联小程序，无法通过自定义菜单跳转！',
			'40164'=>'服务器IP不在白名单导致接口请求失败！请前往公众平台——开发——基本配置——小程序开发信息——IP白名单处设置',
		);
		$code = strval($code);
		if($errors[$code]) {
			return $errors[$code];
		} else {
			return $errmsg;
		}
	}
}